package com.cxy.instarsystem.util;

import com.alibaba.fastjson.JSONObject;
import com.cxy.instarsystem.vo.EncryptResponse;
import com.cxy.instarsystem.vo.SerialNoRespose;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.SecureRandom;
import java.util.Arrays;
import java.util.Objects;

public class DesUtils {

    private static byte[] keyBytes = "4YztMHI7".getBytes(StandardCharsets.UTF_8);
    public static byte[] DES_CBC_Encrypt(byte[] content) {
        try {
            DESKeySpec keySpec = new DESKeySpec(keyBytes);
            SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
            SecretKey key = keyFactory.generateSecret(keySpec);

            Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
            cipher.init(Cipher.ENCRYPT_MODE, key, new IvParameterSpec(keySpec.getKey()));
            byte[] result = cipher.doFinal(content);
            return result;
        } catch (Exception e) {
            System.out.println("exception:" + e.toString());
        }
        return null;
    }

    private static byte[] DES_CBC_Decrypt(byte[] content) {
        try {
            DESKeySpec keySpec = new DESKeySpec(keyBytes);
            SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
            SecretKey key = keyFactory.generateSecret(keySpec);

            Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
            cipher.init(Cipher.DECRYPT_MODE, key, new IvParameterSpec(keyBytes));
            byte[] result = cipher.doFinal(content);
            return result;
        } catch (Exception e) {
            System.out.println("exception:" + e.toString());
        }
        return null;
    }

    private static String byteToHexString(byte[] bytes) {
        StringBuffer sb = new StringBuffer(bytes.length);
        String sTemp;
        for (int i = 0; i < bytes.length; i++) {
            sTemp = Integer.toHexString(0xFF & bytes[i]);
            if (sTemp.length() < 2)
                sb.append(0);
            sb.append(sTemp.toUpperCase());
        }
        return sb.toString();
    }
    public static String encode(String str){
        return byteToHexString(Objects.requireNonNull(DES_CBC_Encrypt(str.getBytes(StandardCharsets.UTF_8))));
    }
    public static void main(String[] args) {
        SerialNoRespose serialNoRespose = new SerialNoRespose();
        serialNoRespose.setCpuId("129486789");
        serialNoRespose.setEncryptSerialNo("121281");
        String beforeData = JSONObject.toJSONString(serialNoRespose);
        System.out.println("加密前：" + beforeData);
        String encrypted = encode(beforeData);
        System.out.println("加密后：" + encrypted);
    }
}
